// 引入store，用于管理socket推送来的消息
import store from '@/store/'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types"
import md5 from 'md5'
// 封装websocket对象
const WS = {
    $ws: null, // webscoket实例
    timeout: 8000, // 心跳重连时间，8秒检测一次
    timeoutObj: null, // 定时器
    lockReconnect: false, // 避免重复重连
    reconnectTimes: 0, // 重连次数

    // 初始化webSocket
    createWS(data) {
            //拼接地址
            let token = Vue.ls.get(ACCESS_TOKEN);
            //将登录token生成一个短的标识
            let wsClientId = md5(token);
            let userId = Vue.ls.get(USER_INFO).id + "_" + wsClientId
            // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
            let url = window._CONFIG['socketURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId
            this.$ws = new WebSocket(url)
            this.$ws.onopen = this.websocketOnopen
            this.$ws.onmessage = this.websocketOnmessage
            this.$ws.onerror = this.websocketOnerror
            this.$ws.onclose = this.websocketOnclose
        
    },

    // webSocket 打开
    websocketOnopen() {
        // WS.$ws.send('Hello WebSockets!')
        store.commit('SET_WS_CONNECT', true)
        console.log('WebSocket连接成功')
        // console.log('== websocket open ==')
        // <!--开始心跳-->
        // WS.wsStartHeart()
    },

    // websocket 接收到服务器消息
    websocketOnmessage: function (msg) {
        // console.log('== websocket message ==', msg)
        let data = JSON.parse(msg.data);
        // 将接收到的消息存到 vuex 中
        store.commit('SET_WS_MSG', data)
        // 每次接收到服务端消息后 重置websocket心跳
        WS.wsRset()
    },

    // websocket 发生错误
    websocketOnerror: function (err) {
        console.log('== websocket error ==', err)
        // 发生错误重连socket
        if (WS.reconnectTimes < 10) {
            WS.wsReconnect()
        }
    },
    // websocket 向后端发送消息
    webSocketSend(messsage) {
        WS.$ws.send(JSON.stringify(messsage))
    },

    // websocket 关闭连接
    // websocketOnclose: function (event) {
    //     console.log('== 关闭websocket连接 ==', event)
    //     if (WS.$ws && WS.$ws.readyState === 1) {
    //         WS.$ws.close()
    //         store.commit('SET_WS_CONNECT', false)
    //     }
    //     let token = Vue.ls.get(ACCESS_TOKEN);
    //     // const token = store.getters.token
    //     if (token) {
    //         if (WS.reconnectTimes < 10) { // 设置重连次数为10次
    //             WS.wsReconnect()
    //         }
    //     }
    // },
    websocketOnclose: function (e) {
        console.log('== 关闭websocket连接 == (' + e + ')')
        if (e) {
            console.log('connection closed (' + e.code + ')')
        }
        // this.wsReconnect()
        WS.wsReconnect()
    },

    // socket开始心跳
    wsStartHeart: function () {
        // WS.timeoutObj && clearTimeout(WS.timeoutObj)
        WS.timeoutObj = setTimeout(function () {
            // 后端要求的参数格式（具体可根据自己的进行修改）
            let params = {
                contJson: {},
                contactMethodTypeEnum: 'HEARTBEAT_DETECTION', // 心跳检测
            }
            // console.log('心跳中~~~')
            WS.$ws.send(JSON.stringify(params))
        }, WS.timeout)
    },

    // socket 重置心跳
    wsRset: function () {
        clearTimeout(WS.timeoutObj)
        // WS.wsStartHeart()
    },

    // socket 重连
    // wsReconnect: function () {
    //     debugger
    //     console.log('Reconnection Socket')
    //     // eslint-disable-next-line no-undef
    //     if (WS.lockReconnect) return
    //     WS.reconnectTimes++
    //     WS.lockReconnect = true
    //     const userInfo = JSON.parse(window.localStorage.getItem('justech-userInfo'));
    //     // console.log(userInfo, 'userInfo')
    //     setTimeout(function () { // 没连接上会一直重连，设置延迟避免请求过多
    //         WS.createWS(userInfo.content)
    //         WS.lockReconnect = false
    //     }, 6000)
    // },
    wsReconnect() {
        var that = this
        if (that.lockReconnect) return
        that.lockReconnect = true
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
            console.info('尝试重连...')
            that.createWS()
            that.lockReconnect = false
        }, 5000)
    },
}

export default WS